﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Utility;
//using VAdvantage.Controls;
using VAdvantage.Classes;
using VAdvantage.Model;
using VAdvantage.Framework;
using System.Data;
using VAdvantage.Logging;
using System.Text;
using VAdvantage.DataBase;
using System.Collections;
using SLControls.Controls;
using VAdvantage.Controls;
using VAdvantage.SqlExec;
using System.ComponentModel;
using VAdvantage.Grids;
using System.Windows.Data;

namespace VAdvantage.Apps.AForms
{
    public partial class VMatch : UserControl, FormPanel
    {
        #region PrivateVariables

        private const long SERIALVERSIONUID = 1L;
        //Window No		
        private int _WindowNo = 0;
        //FormFrame			
        private FormFrame _frame;
        //Logger				
        static VLogger log = VLogger.GetVLogger(typeof(VMatch).FullName);

        private int _AD_Client_ID = Envs.GetCtx().GetAD_Client_ID();
        private int _AD_Org_ID = Envs.GetCtx().GetAD_Org_ID();
        private int _by = Envs.GetCtx().GetAD_User_ID();

        //Match Options           
        private String[] _matchOptions = new String[]
    {
		Msg.GetElement(Envs.GetCtx(), "C_Invoice_ID", false),
		Msg.GetElement(Envs.GetCtx(), "M_InOut_ID", false),
		Msg.GetElement(Envs.GetCtx(), "C_Order_ID", false) };

        private const int MATCH_INVOICE = 0;
        private const int MATCH_SHIPMENT = 1;
        private const int MATCH_ORDER = 2;

        // Match Mode              	
        private String[] _matchMode = new String[] 
    {
		Msg.Translate(Envs.GetCtx(), "NotMatched"),
		Msg.Translate(Envs.GetCtx(), "Matched")};

        private const int MODE_NOTMATCHED = 0;
        private const int MODE_MATCHED = 1;

        //Indexes in Table			
        private const int I_BPartner = 5;
        private const int I_Line = 6;
        private const int I_Product = 9;
        private const int I_QTY = 10;
        private const int I_MATCHED = 11;


        private StringBuilder _sql = null;
        private String _dateColumn = "";
        private String _qtyColumn = "";
        private String _groupBy = "";

        private Decimal _xMatched = Envs.ZERO;
        private Decimal _xMatchedTo = Envs.ZERO;

        //
        //private CComboBox cmbMatchFrom = new CComboBox(_matchOptions);
        private VTextBoxButton vOnlyVendor = null;
        private VTextBoxButton vOnlyProduct = null;


        Grids.MyDataGridCheckBoxColumn chk = new MyDataGridCheckBoxColumn();
        #endregion

        public VMatch()
        {
            InitializeComponent();
        }
        public void Init(int WindowNo, FormFrame frame)
        {

            _WindowNo = WindowNo;
            _frame = frame;
            //_frame.Height = App.Current.Host.Content.ActualHeight - 25;
            //_frame.Width = App.Current.Host.Content.ActualWidth;

            Envs.GetCtx().SetIsSOTrx(_WindowNo, true);

            this.Visibility = System.Windows.Visibility.Visible;
            _frame.ContentGrid.Children.Add(this);
            LayoutRoot.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            SetBusy(true);
            GetLookUp();
            // vcmbMatchFrom.Items.Add(_matchOptions);
            vcmbMatchFrom.ItemsSource = _matchOptions;
            vcmbMatchMode.ItemsSource = _matchMode;
            /// vcmbMatchMode.Items.Add(_matchMode);

            vcmbMatchFrom.SelectedIndex = 0;
            vcmbMatchMode.SelectedIndex = 0;

            _WindowNo = WindowNo;
            _frame = frame;
            log.Info("WinNo=" + _WindowNo
                + " - AD_Client_ID=" + _AD_Client_ID + ", AD_Org_ID=" + _AD_Org_ID + ", By=" + _by);
            Envs.GetCtx().SetIsSOTrx(_WindowNo, false);
            try
            {
                //  BPartner
                int AD_Column_ID = 3499; //C_Invoice.C_BPartner_ID
                //Lookup lookupBP = MLookupFactory.Get(Envs.GetCtx(), WindowNo, AD_Column_ID, VAdvantage.Classes.DisplayType.Search);
                //vOnlyVendor = new VTextBoxButton("C_BPartner_ID", false, false, true, VAdvantage.Classes.DisplayType.Search, lookupBP);

                ////Product
                //AD_Column_ID = 3840; // C_InvoiceLine.M_Product_ID
                //Lookup lookupPro = MLookupFactory.Get(Envs.GetCtx(), WindowNo,
                //AD_Column_ID, VAdvantage.Classes.DisplayType.Search);
                //vOnlyProduct = new VTextBoxButton("M_Product_ID", false, false, true, VAdvantage.Classes.DisplayType.Search, lookupPro);

                //InitDesign();
                DynInit();

                // Worker.RunWorkerAsync();
                // Application.DoEvents();
                //frame.Size = new Size(800, 600);
                //frame.GetContentPane().Controls.Add((Control)this);
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "", e);
            }
            chk.Click += new RoutedEventHandler(chk_Click);
            chk.PropertyChanged += new PropertyChangedEventHandler(chk_PropertyChanged);
        }


        private void SetBusy(bool value)
        {

            this.IsEnabled = !value;
            busyWindow.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtBusy.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }
        public void Dispose()
        {
            if (_frame != null)
            {
                _frame.Dispose();
            }
            _frame = null;
        }

        public void GetLookUp()
        {

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                //BPartners
                int AD_Column_ID = 3499;
                Lookup lookupBP = MLookupFactory.Get(Envs.GetCtx(), _WindowNo, AD_Column_ID, VAdvantage.Classes.DisplayType.Search);

                //Product
                AD_Column_ID = 3840; // C_InvoiceLine.M_Product_ID
                Lookup lookupPro = MLookupFactory.Get(Envs.GetCtx(), _WindowNo, AD_Column_ID, VAdvantage.Classes.DisplayType.Search);

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => InitDesign(lookupBP, lookupPro));

            });
        }

        /// <summary>
        /// Static Init.
        ///  <pre>
        ///  mainPanel
        ///      northPanel
        ///      centerPanel
        ///          txtMatched
        ///          xPanel
        ///          xMathedTo
        ///      southPanel
        ///  </pre>
        /// </summary>
        private void InitDesign(Lookup lookupBP, Lookup lookupPro)
        {
            vlblMatchFrom.Content = (Msg.Translate(Envs.GetCtx(), "MatchFrom"));
            vlblMatchTo.Content = (Msg.Translate(Envs.GetCtx(), "MatchTo"));
            vlblMatchMode.Content = (Msg.Translate(Envs.GetCtx(), "MatchMode"));
            vchkIsReturnTrx.IsChecked = false;
            vchkIsReturnTrx.Content = (Msg.Translate(Envs.GetCtx(), "isReturnTrx"));
            vlblBPartner.Content = (Msg.Translate(Envs.GetCtx(), "C_BPartner_ID"));
            vlblProduct.Content = (Msg.Translate(Envs.GetCtx(), "M_Product_ID"));
            vlblDateFrom.Content = (Msg.Translate(Envs.GetCtx(), "DateFrom"));
            vlblDateTo.Content = (Msg.Translate(Envs.GetCtx(), "DateTo"));
            vbtnSearch.Content = (Msg.Translate(Envs.GetCtx(), "Search"));

            vlblMatched.Content = (Msg.Translate(Envs.GetCtx(), "ToBeMatched"));
            vlblMatchedTo.Content = (Msg.Translate(Envs.GetCtx(), "Matching"));
            vlblDifference.Content = (Msg.Translate(Envs.GetCtx(), "Difference"));
            vbtnProcess.Content = (Msg.Translate(Envs.GetCtx(), "Process"));
            vbtnProcess.IsEnabled = false;

            vchkSameProduct.IsChecked = true;
            vchkSameProduct.Content = (Msg.Translate(Envs.GetCtx(), "SameProduct"));
            vchkSameBPartner.IsChecked = true;
            vchkSameBPartner.Content = (Msg.Translate(Envs.GetCtx(), "SameBPartner"));
            vchkSameQty.IsChecked = false;
            vchkSameQty.Content = (Msg.Translate(Envs.GetCtx(), "SameQty"));

            // 
            // vOnlyVendor
            // 
            vOnlyVendor = new VTextBoxButton("C_BPartner_ID", false, false, true, VAdvantage.Classes.DisplayType.Search, lookupBP);
            this.vOnlyVendor.HorizontalAlignment = HorizontalAlignment.Stretch;
            //this.vOnlyVendor.EditingControlRowIndex = 0;
            //this.vOnlyVendor.EditingControlValueChanged = false;
            //this.vOnlyVendor.Location = new System.Drawing.Point(230, 57);
            this.vOnlyVendor.Name = "vOnlyVendor";
            //this.vOnlyVendor.RightToLeft = System.Windows.Forms.RightToLeft.No;
            //this.vOnlyVendor.Size = new System.Drawing.Size(147, 20);
            this.vOnlyVendor.TabIndex = 31;
            this.vOnlyVendor.TextSetting = false;
            this.vOnlyVendor.Value = null;
            /// this.tblpMain.Controls.Add(this.vOnlyVendor, 2, 2);
            this.vdgvInnerGrid.Children.Add(vOnlyVendor);
            Grid.SetRow(vOnlyVendor, 1);
            Grid.SetColumn(vOnlyVendor, 1);
            vOnlyVendor.Margin = new Thickness(0, 5, 5, 0);


            // 
            // vOnlyProduct
            // 
            vOnlyProduct = new VTextBoxButton("M_Product_ID", false, false, true, VAdvantage.Classes.DisplayType.Search, lookupPro);
            this.vOnlyProduct.HorizontalAlignment = HorizontalAlignment.Stretch;
            //this.vOnlyProduct.EditingControlRowIndex = 0;
            //this.vOnlyProduct.EditingControlValueChanged = false;
            //this.vOnlyProduct.Location = new System.Drawing.Point(484, 57);
            this.vOnlyProduct.Name = "vOnlyProduct";
            //this.vOnlyProduct.RightToLeft = System.Windows.Forms.RightToLeft.No;
            //this.vOnlyProduct.Size = new System.Drawing.Size(160, 20);
            this.vOnlyProduct.TabIndex = 33;
            this.vOnlyProduct.TextSetting = false;
            this.vOnlyProduct.Value = null;
            vdgvInnerGrid.Children.Add(vOnlyProduct);
            Grid.SetRow(vOnlyProduct, 1);
            Grid.SetColumn(vOnlyProduct, 3);
            vOnlyProduct.Margin = new Thickness(0, 5, 5, 0);


            SetBusy(false);
            //CommonFunctions.SetDataGridPrperties(vdgvInvoice);
            //CommonFunctions.SetDataGridPrperties(vdgvReceipt);
            //CommonStyle(vdgvInvoice);
            //CommonStyle(vdgvReceipt);
        }

        /// <summary>
        /// Dynamic Init.
        /// Table Layout, Visual, Listener
        /// </summary>
        private void DynInit()
        {

            Cmd_MatchFrom();
            vStatusBar.SetStatusLine("");
            vStatusBar.SetStatusDB(0);
        }
        //private void AddColumns(bool isReceipt)
        //{
        //    if (_Layout == null)
        //    {
        //        _Layout = new Info_Column[]
        //            {
        //                //new Info_Column(" ",".",typeof(IDColumn), false, false, ""),
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "DocumentNo"),   ".", typeof(String)),             //  1
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "Date"),         ".", typeof(DateTime)),
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "C_BPartner_ID"),".", typeof(KeyNamePair), "."),   //  3
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "Line"),         ".", typeof(KeyNamePair), "."),
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "M_Product_ID"), ".", typeof(KeyNamePair), "."),   //  5
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "Qty"),          ".", typeof(Double)),
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "Matched"),      ".", typeof(Double))
        //                //new Info_Column(" ",".",typeof(IDColumn), false, false, ""),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(),"SelectRow"),".",typeof(bool)),
        //                new Info_Column(" ",".",typeof(IDColumn), false, false, ""),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "DocumentNo"),   ".", typeof(String)),             //  1
        //                new Info_Column(Msg.Translate(Envs.GetCtx(),"Business Partner"),".",typeof(String)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "Date"),         ".", typeof(DateTime)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "C_BPartner_ID"),".", typeof(int)),   //  3
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "Line"),         ".", typeof(int)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(),"C_InvoiceLine_ID"),".",typeof(int)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(),"Product"),".",typeof(String)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "M_Product_ID"), ".", typeof(int)),   //  5
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "Qty"),          ".", typeof(Double)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "Matched"),      ".", typeof(Double))
        //            };
        //    }

        //    DataTable dt = new DataTable();
        //    DataColumn dc = null;
        //    for (int col = 0; col < _Layout.Length; col++)
        //    {
        //        Type c = _Layout[col].GetColClass();
        //        if (c == typeof(IDColumn))
        //        {
        //            dc = new DataColumn(_Layout[col].GetColHeader(), typeof(IDColumn));
        //            dt.Columns.Add(dc);

        //        }
        //        else if (c == typeof(String))
        //        {
        //            dc = new DataColumn(_Layout[col].GetColHeader(), typeof(String));
        //            dt.Columns.Add(dc);
        //        }
        //        else if (c == typeof(DateTime))
        //        {
        //            dc = new DataColumn(_Layout[col].GetColHeader(), typeof(DateTime));
        //            dt.Columns.Add(dc);
        //        }
        //        else if (c == typeof(KeyNamePair))
        //        {
        //            dc = new DataColumn(_Layout[col].GetColHeader(), typeof(KeyNamePair));
        //            dt.Columns.Add(dc);
        //        }
        //        else if (c == typeof(Double))
        //        {
        //            dc = new DataColumn(_Layout[col].GetColHeader(), typeof(Double));
        //            dt.Columns.Add(dc);
        //        }

        //    }
        //    if (!isReceipt)
        //    {
        //        vdgvInvoice.ItemsSource = null;
        //        vdgvInvoice.ItemsSource = dt.GetBindableData(new Connector());
        //        vdgvInvoice.Columns[0].Visibility = Visibility.Collapsed;
        //        vdgvInvoice.IsReadOnly = true;
        //    }
        //    else
        //    {
        //        vdgvReceipt.ItemsSource = null;
        //        if (vdgvReceipt.Columns.Count > 0)
        //        {
        //            vdgvReceipt.Columns.Clear();
        //        }
        //        vdgvReceipt.ItemsSource = dt.GetBindableData(new Connector());
        //        vdgvReceipt.Columns[0].Visibility = Visibility.Collapsed;
        //    }
        //}

        Info_Column[] _Layout = null;
        //private void AddColumns()
        //{
        //    if (_Layout == null)
        //    {
        //        _Layout = new Info_Column[]
        //            {
        //                //new Info_Column(" ",".",typeof(IDColumn), false, false, ""),
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "DocumentNo"),   ".", typeof(String)),             //  1
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "Date"),         ".", typeof(DateTime)),
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "C_BPartner_ID"),".", typeof(KeyNamePair), "."),   //  3
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "Line"),         ".", typeof(KeyNamePair), "."),
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "M_Product_ID"), ".", typeof(KeyNamePair), "."),   //  5
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "Qty"),          ".", typeof(Double)),
        //                //new Info_Column(Msg.Translate(Envs.GetCtx(), "Matched"),      ".", typeof(Double))
        //                new Info_Column(Msg.Translate(Envs.GetCtx(),"SelectRow"),".",typeof(bool)),
        //                new Info_Column(" ",".",typeof(IDColumn), false, false, ""),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "Document No"),   ".", typeof(String)),             //  1
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "Date"),         ".", typeof(DateTime)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(),"Business Partner"),".",typeof(String)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "C_BPartner_ID"),".", typeof(int)),   //  3
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "Line"),         ".", typeof(int)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(),"C_InvoiceLine_ID"),".",typeof(int)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(),"Product"),".",typeof(String)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "M_Product_ID"), ".", typeof(int)),   //  5
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "Qty"),          ".", typeof(Double)),
        //                new Info_Column(Msg.Translate(Envs.GetCtx(), "Matched"),      ".", typeof(Double))
        //            };
        //    }

        //    DataTable dt = new DataTable();
        //    DataColumn dc = null;
        //    for (int col = 0; col < _Layout.Length; col++)
        //    {
        //        Type c = _Layout[col].GetColClass();
        //        if (c == typeof(IDColumn))
        //        {
        //            dc = new DataColumn(_Layout[col].GetColHeader(), typeof(IDColumn));
        //            dt.Columns.Add(dc);
        //        }
        //        else if (c == typeof(String))
        //        {
        //            dc = new DataColumn(_Layout[col].GetColHeader(), typeof(String));
        //            dt.Columns.Add(dc);
        //        }
        //        else if (c == typeof(DateTime))
        //        {
        //            dc = new DataColumn(_Layout[col].GetColHeader(), typeof(DateTime));
        //            dt.Columns.Add(dc);
        //        }
        //        else if (c == typeof(KeyNamePair))
        //        {
        //            dc = new DataColumn(_Layout[col].GetColHeader(), typeof(KeyNamePair));
        //            dt.Columns.Add(dc);
        //        }
        //        else if (c == typeof(Double))
        //        {
        //            dc = new DataColumn(_Layout[col].GetColHeader(), typeof(Double));
        //            dt.Columns.Add(dc);
        //        }

        //    }
        //    vdgvInvoice.ItemsSource = null;
        //    vdgvReceipt.ItemsSource = null;
        //    vdgvInvoice.ItemsSource = dt.GetBindableData(new Connector());
        //    // vdgvInvoice.Columns[0].Visibility = Visibility.Collapsed;

        //    vdgvInvoice.IsReadOnly = true;


        //    //1.Select column
        //    if (vdgvReceipt.Columns.Count > 0)
        //    {
        //        vdgvReceipt.Columns.Clear();
        //    }
        //    vdgvReceipt.ItemsSource = dt.GetBindableData(new Connector());
        //    //vdgvReceipt.Columns[0].Visibility = Visibility.Collapsed;



        //}

        /// <summary>
        /// Process Button Pressed - Process Matching
        /// </summary>
        private void Cmd_Process()
        {
            //IList rowInvoice = vdgvInvoice.ItemsSource as IList;
            //IList rowRecepit = vdgvReceipt.ItemsSource as IList;

            BindingSource rowInvoice = vdgvInvoice.ItemsSource as BindingSource;
            BindingSource rowRecepit = vdgvReceipt.ItemsSource as BindingSource;
            log.Config("");
            //  Matched From
            //int matchedRow = xMatchedTable.getSelectedRow();
            int matchedRow = -1;
            if (vdgvInvoice.SelectedItems.Count > 0)
            {
                if (vdgvInvoice.SelectedIndex == null)
                {
                    matchedRow = 0;
                }
                else
                {
                    matchedRow = vdgvInvoice.SelectedIndex;
                }
            }
            if (matchedRow < 0)
                return;
            //KeyNamePair BPartner = (KeyNamePair)vdgvInvoice.Rows[matchedRow].Cells[I_BPartner].Value;
            //KeyNamePair lineMatched = (KeyNamePair)vdgvInvoice.Rows[matchedRow].Cells[I_Line].Value;
            //KeyNamePair Product = (KeyNamePair)vdgvInvoice.Rows[matchedRow].Cells[I_Product].Value;

            int BPartner = Convert.ToInt32(((BindableObject)rowInvoice[matchedRow]).GetValue(I_BPartner));
            int lineMatched = Convert.ToInt32(((BindableObject)rowInvoice[matchedRow]).GetValue(I_Line + 1));
            int Product = Convert.ToInt32(((BindableObject)rowInvoice[matchedRow]).GetValue(I_Product));

            //Product.GetKey();
            double toMatchQty = Util.GetValueOfDouble(_xMatched);
            //double matchedQty = Util.GetValueOfDouble(vdgvInvoice.Rows[matchedRow].Cells[I_MATCHED].Value);
            double matchedQty = Util.GetValueOfDouble(((BindableObject)rowInvoice[matchedRow]).GetValue(I_MATCHED));

            int val = 1;
            //  Matched To
            bool notMatched = false;
            if (vcmbMatchMode.SelectedIndex == MODE_NOTMATCHED)
            {
                notMatched = true;
            }

            bool matchOrder = false;
            if (vcmbMatchFrom.SelectedItem.Equals(_matchOptions[MATCH_ORDER]))
            {
                matchOrder = true;
            }
            bool matchOrder2 = false;
            if (vcmbMatchTo.SelectedItem.Equals(_matchOptions[MATCH_ORDER]))
            {
                matchOrder2 = true;
            }

            bool matchShi = false;
            if (vcmbMatchFrom.SelectedIndex == MATCH_SHIPMENT)
            {
                matchShi = true;
            }

            SetBusy(true);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                for (int row = 0; row < rowRecepit.Count; row++)
                {
                    //IDColumn id = (IDColumn)vdgvReceipt.Rows[row].Cells[1].Value;
                    //IDColumn id = (IDColumn)((BindableObject)rowRecepit[row]).GetValue(1);
                    if (Convert.ToBoolean(((BindableObject)rowRecepit[row]).GetValue("SELECTROW")))
                    {
                        int id = Convert.ToInt32(((BindableObject)rowRecepit[row]).GetValue(1));
                        //if (id != null && id.IsSelected())
                        if (id != 0 && bVal == true)
                        {
                            //  need to be the same product
                            //KeyNamePair ProductCompare = (KeyNamePair)vdgvReceipt.Rows[row].Cells[I_Product + val].Value;
                            int ProductCompare = Convert.ToInt32(((BindableObject)rowRecepit[row]).GetValue(I_Product));
                            if (Product != ProductCompare)
                                continue;
                            //KeyNamePair lineMatchedTo = (KeyNamePair)vdgvReceipt.Rows[row].Cells[I_Line + val].Value;
                            int lineMatchedTo = Convert.ToInt32(((BindableObject)rowRecepit[row]).GetValue(I_Line + val));


                            //	Qty
                            double qty = 0.0;

                            //if (vcmbMatchMode.SelectedIndex == MODE_NOTMATCHED)
                            //    qty = Util.GetValueOfDouble(vdgvReceipt.Rows[row].Cells[I_QTY + val].Value);// doc                    
                            //qty -= Util.GetValueOfDouble(vdgvReceipt.Rows[row].Cells[I_MATCHED + val].Value);

                            if (notMatched)
                                qty = Util.GetValueOfDouble(((BindableObject)rowRecepit[row]).GetValue(I_QTY));// doc                    
                            qty -= Util.GetValueOfDouble(((BindableObject)rowRecepit[row]).GetValue(I_MATCHED));


                            if (notMatched)
                            {
                                if (qty > toMatchQty)
                                {
                                    qty = toMatchQty;
                                }
                                toMatchQty -= qty;
                            }
                            else
                            {
                                if (Math.Abs(qty) > matchedQty)
                                    qty = -matchedQty;
                                matchedQty += qty;
                            }

                            //  Invoice or PO
                            Boolean invoice = true;
                            //if (cmbMatchFrom.SelectedItem == MATCH_ORDER ||
                            //cmbMatchTo.getSelectedItem().equals(_matchOptions[MATCH_ORDER]))
                            if (matchOrder || matchOrder2)
                                invoice = false;
                            //  Get Shipment_ID
                            int M_InOutLine_ID = 0;
                            int Line_ID = 0;
                            if (matchShi)
                            {
                                M_InOutLine_ID = lineMatched;      //  upper table
                                Line_ID = lineMatchedTo;
                            }
                            else
                            {
                                M_InOutLine_ID = lineMatchedTo;    //  lower table
                                Line_ID = lineMatched;
                            }

                            //  Create it
                            CreateMatchRecord(invoice, M_InOutLine_ID, Line_ID, Util.GetValueOfDecimal(qty));
                        }
                    }
                }
                Dispatcher.BeginInvoke(() => Requery(lineMatched));
            });
            //  requery
            //// Cmd_Search();
            //ShowMessage.Info("Processed Line No: " + lineMatched.ToString(), null, "", "");
        }

        public void Requery(int lineMatched)
        {
            Cmd_Search();
            ShowMessage.Info("ProcessedLineNo" + lineMatched.ToString(), null, "", "");
        }

        /// <summary>
        /// Match From Changed - Fill Match To
        /// </summary>
        private void Cmd_MatchFrom()
        {
            log.Fine("VMatch.cmd_matchFrom");
            //String selection = (String)cmbMatchFrom.getSelectedItem();
            String selection = null;
            if (vcmbMatchFrom.Items.Count > 0)
            {
                selection = Util.GetValueOfString(vcmbMatchFrom.SelectedItem);
                //Vector<String> vector = new Vector<String>(2);
                List<String> vector = new List<String>(2);

                if (selection.Equals(_matchOptions[MATCH_INVOICE]))
                {
                    vector.Add(_matchOptions[MATCH_SHIPMENT]);
                }
                else if (selection.Equals(_matchOptions[MATCH_ORDER]))
                {
                    vector.Add(_matchOptions[MATCH_SHIPMENT]);
                }
                else    //  shipment
                {
                    vector.Add(_matchOptions[MATCH_INVOICE]);
                    vector.Add(_matchOptions[MATCH_ORDER]);
                }
                //cmbMatchTo.setModel(new DefaultComboBoxModel(vector));
                //vcmbMatchTo.Items.Clear();
                //vcmbMatchTo.Items.Add(vector.ToArray());
                vcmbMatchTo.ItemsSource = vector.ToArray();
                vcmbMatchTo.SelectedIndex = 0;
                //  Set Title
                //xMatchedBorder.setTitle(selection);
                vlblInvoice.Content = selection;

            }
            //  Reset Table
            //xMatchedTable.setRowCount(0);
            //vdgvInvoice.RowCount = 0;
            //  sync To
            Cmd_MatchTo();
        }

        /// <summary>
        ///  Match To Changed - set Title
        /// </summary>
        private void Cmd_MatchTo()
        {
            log.Fine("VMatch.cmd_matchTo");
            String selection = Util.GetValueOfString(vcmbMatchTo.SelectedItem);
            //xMatchedToBorder.setTitle(selection);
            vlblReceipt.Content = selection;
            //xMatchedToScrollPane.repaint();
            //  Reset Table
            // xMatchedToTable.setRowCount(0);
            //vdgvReceipt.RowCount = 0;
            
        }

        bool txtchange = false;

        /// <summary>
        /// Search Button Pressed - Fill txtMatched
        /// </summary>
        private void Cmd_Search()
        {
            if (vdgvInvoice.ItemsSource != null)
            {
                vdgvInvoice.ItemsSource = null;
            }
            if (vdgvReceipt.ItemsSource != null)
            {
                vdgvReceipt.ItemsSource=null;
            }
            //Create SQL 
            //String matchToString = (String)cmbMatchTo.getSelectedItem();
            int display = Util.GetValueOfInt(vcmbMatchFrom.SelectedIndex);
            String matchToString = Util.GetValueOfString(vcmbMatchTo.SelectedItem);

            int matchToType = MATCH_INVOICE;
            if (matchToString.Equals(_matchOptions[MATCH_SHIPMENT]))
            {
                matchToType = MATCH_SHIPMENT;
            }
            else if (matchToString.Equals(_matchOptions[MATCH_ORDER]))
            {
                matchToType = MATCH_ORDER;
            }

            TableInit(display, matchToType);	//	sets _sql

            //Add Where Clause 
            //  Product
            if (vOnlyProduct.GetValue() != null)
            {
                int Product = Util.GetValueOfInt(vOnlyProduct.GetValue());
                _sql.Append(" AND lin.M_Product_ID=").Append(Product);
            }
            //  BPartner
            if (vOnlyVendor.GetValue() != null)
            {
                int Vendor = Util.GetValueOfInt(vOnlyVendor.GetValue());
                _sql.Append(" AND hdr.C_BPartner_ID=").Append(Vendor);
            }
            //  Date
            DateTime? from = null; 
            DateTime? to = null;
            
            if (vdtpFrom.GetValue() != null)
            {
                from = Util.GetValueOfDateTime(vdtpFrom.GetValue());
            }
            if (vdtpTo.GetValue() != null)
            {
                to = Util.GetValueOfDateTime(vdtpTo.GetValue());
            }
            if (from != null && to != null)
            {
                _sql.Append(" AND ").Append(_dateColumn).Append(" BETWEEN ")
                    .Append(DB.TO_DATE(from)).Append(" AND ").Append(DB.TO_DATE(to));
            }
            else if (from != null)
            {
                _sql.Append(" AND ").Append(_dateColumn).Append(" >= ").Append(DB.TO_DATE(from));
            }
            else if (to != null)
            {
                _sql.Append(" AND ").Append(_dateColumn).Append(" <= ").Append(DB.TO_DATE(to));
            }

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {

                //  ** Load Table **
                DataSet ds = TableLoad(vdgvInvoice);//xMatchedTable

                //vtxtMatched.SetValue(Envs.ZERO);
                Dispatcher.BeginInvoke(delegate
                {
                    ExecuteQuery(vdgvInvoice, ds);
                    vtxtMatched.Text = Envs.ZERO.ToString();


                    txtchange = true;
                  
                    BindingSource rowInvoice = vdgvInvoice.ItemsSource as BindingSource;
                    BindingSource rowReceipt = vdgvReceipt.ItemsSource as BindingSource;

                    int rowIn = rowInvoice != null ? rowInvoice.Count : 0;
                    int rowRe = rowReceipt != null ? rowReceipt.Count : 0;

                    vStatusBar.SetStatusLine(vcmbMatchFrom.SelectedItem.ToString()
                        + "# = " + rowIn + " -" + vcmbMatchTo.SelectedItem.ToString() + "# = " + rowRe,
                        rowIn == 0);
                    vStatusBar.SetStatusDB(0);
                    SetBusy(false);
                });
            });

        }

        /// <summary>
        /// Fill txtMatchedTo
        /// </summary>
        private void Cmd_SearchTo()
        {
            //IList rowInvoice = vdgvInvoice.ItemsSource as IList;
            //IList rowReceipt = vdgvReceipt.ItemsSource as IList;

            BindingSource rowInvoice = vdgvInvoice.ItemsSource as BindingSource;
            BindingSource rowReceipt = vdgvReceipt.ItemsSource as BindingSource;

            int row = -1;
            if (vdgvInvoice.SelectedItems.Count > 0)
            {
                if (vdgvInvoice.SelectedIndex == null)
                {
                    row = 0;
                }
                else
                {
                    row = vdgvInvoice.SelectedIndex;
                }
            }
            log.Config("Row=" + row);

            double qty = 0.0;
            if (row < 0)
            {

            }
            else
            {
                //  ** Create SQL **
                String displayString = Util.GetValueOfString(vcmbMatchTo.SelectedItem);
                int display = MATCH_INVOICE;
                if (displayString.Equals(_matchOptions[MATCH_SHIPMENT]))
                {
                    display = MATCH_SHIPMENT;
                }
                else if (displayString.Equals(_matchOptions[MATCH_ORDER]))
                {
                    display = MATCH_ORDER;
                }
                int matchToType = vcmbMatchFrom.SelectedIndex;
                TableInit(display, matchToType);	//	sets _sql
                //  ** Add Where Clause **
                //KeyNamePair BPartner = (KeyNamePair)vdgvInvoice.Rows[row].Cells[I_BPartner].Value;
                //KeyNamePair Product = (KeyNamePair)vdgvInvoice.Rows[row].Cells[I_Product].Value;

                int BPartner = Convert.ToInt32(((BindableObject)rowInvoice[row]).GetValue(I_BPartner));
                int Product = Convert.ToInt32(((BindableObject)rowInvoice[row]).GetValue(I_Product));

                log.Fine("BPartner=" + BPartner + " - Product=" + Product);
                //
                if ((bool)vchkSameBPartner.IsChecked)
                {
                    _sql.Append(" AND hdr.C_BPartner_ID=").Append(BPartner);
                }
                if ((bool)vchkSameProduct.IsChecked)
                {
                    _sql.Append(" AND lin.M_Product_ID=").Append(Product);
                }

                //  calculate qty
                //double docQty = Util.GetValueOfDouble(vdgvInvoice.Rows[row].Cells[I_QTY].Value);
                //double matchedQty = Util.GetValueOfDouble(vdgvInvoice.Rows[row].Cells[I_MATCHED].Value);

                double docQty = Util.GetValueOfDouble(((BindableObject)rowInvoice[row]).GetValue(I_QTY));
                double matchedQty = Util.GetValueOfDouble(((BindableObject)rowInvoice[row]).GetValue(I_MATCHED));

                qty = docQty - matchedQty;
                if ((bool)vchkSameQty.IsChecked)
                {
                    _sql.Append(" AND ").Append(_qtyColumn).Append("=").Append(docQty);
                }
                SetBusy(true);

                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    //Load Table Recipt table
                    DataSet ds = TableLoad(vdgvReceipt);//xMatchedToTable
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        ExecuteQuery(vdgvReceipt, ds);
                        SetValues(qty, rowInvoice, rowReceipt);
                    });
                });
                //  Display To be Matched Qty
            }
        }

        public void SetValues(double qty, BindingSource rowInvoice, BindingSource rowReceipt)
        {
            _xMatched = Util.GetValueOfDecimal(qty);
            if (txtchange)
            {
                vtxtMatched.Text = Envs.ZERO.ToString();
                txtchange = false;
            }
            else
            {
                vtxtMatched.Text = _xMatched.ToString();
            }
            vtxtMatchedTo.Text = Envs.ZERO.ToString();
            vtxtDifference.Text = _xMatched.ToString();
            //  Status Info
            //vStatusBar.SetStatusLine(cmbMatchFrom.SelectedItem.ToString()
            //    + "# = " + xMatchedTable.getRowCount() + " - "
            //    + cmbMatchTo.SelectedItem.ToString()
            //    + "# = " + xMatchedToTable.getRowCount(),
            //    xMatchedToTable.getRowCount() == 0);


            int rowIn = rowInvoice != null ? rowInvoice.Count : 0;
            int rowRe = rowReceipt != null ? rowReceipt.Count : 0;

            vStatusBar.SetStatusLine(vcmbMatchFrom.SelectedItem.ToString()
                + "# = " + rowIn + " - "
                + vcmbMatchTo.SelectedItem + "# = " + rowRe,
                rowRe == 0);

            vStatusBar.SetStatusDB(0);
            SetBusy(false);
        }

        int checkGrid = 0;

        /// <summary>
        /// Initialise Table access - create SQL, dateColumn.
        ///  <br>
        ///  The driving table is "hdr", e.g. for hdr.C_BPartner_ID=..
        ///  The line table is "lin", e.g. for lin.M_Product_ID=..
        ///  You use the dateColumn/qtyColumn variable directly as it is table specific.
        ///  <br>
        ///  The sql is dependent on MatchMode:
        ///  - If Matched - all (fully or partially) matched records are listed
        ///  - If Not Matched - all not fully matched records are listed
        /// </summary>
        /// <param name="display">(Invoice, Shipment, Order) see MATCH_</param>
        /// <param name="matchToType">(Invoice, Shipment, Order) see MATCH_</param>
        private void TableInit(int display, int matchToType)
        {
            Boolean matched = vcmbMatchMode.SelectedIndex == MODE_MATCHED;
            log.Config("Display=" + _matchOptions[display]
                + ", MatchTo=" + _matchOptions[matchToType]
                + ", Matched=" + matched);


            _sql = new StringBuilder();
            if (display == MATCH_INVOICE)
            {
                checkGrid = 1;
                _dateColumn = "hdr.DateInvoiced";
                _qtyColumn = "lin.QtyInvoiced";
                _sql.Append("SELECT 'false' as SELECTROW,hdr.C_Invoice_ID AS C_INVOICE_ID ,hdr.DocumentNo AS DOCUMENTNO, hdr.DateInvoiced AS DATE1, bp.Name AS BPNAME,hdr.C_BPartner_ID AS C_BPARTNER_ID,"
                    + " lin.Line AS LINE,lin.C_InvoiceLine_ID AS C_INVOICELINE_ID, p.Name AS PNAME,lin.M_Product_ID AS M_PRODUCT_ID,"
                    + " lin.QtyInvoiced AS QTYINVOICED,SUM(NVL(mi.Qty,0)) AS MQTY "
                    + "FROM C_Invoice hdr"
                    + " INNER JOIN C_BPartner bp ON (hdr.C_BPartner_ID=bp.C_BPartner_ID)"
                    + " INNER JOIN C_InvoiceLine lin ON (hdr.C_Invoice_ID=lin.C_Invoice_ID)"
                    + " INNER JOIN M_Product p ON (lin.M_Product_ID=p.M_Product_ID)"
                    + " INNER JOIN C_DocType dt ON (hdr.C_DocType_ID=dt.C_DocType_ID and dt.DocBaseType in ('API','APC') AND dt.IsReturnTrx = ")
                    .Append(((bool)vchkIsReturnTrx.IsChecked) ? "'Y')" : "'N')")
                    .Append(" FULL JOIN M_MatchInv mi ON (lin.C_InvoiceLine_ID=mi.C_InvoiceLine_ID) "
                    + "WHERE hdr.DocStatus IN ('CO','CL')");
                _groupBy = " GROUP BY hdr.C_Invoice_ID,hdr.DocumentNo,hdr.DateInvoiced,bp.Name,hdr.C_BPartner_ID,"
                    + " lin.Line,lin.C_InvoiceLine_ID,p.Name,lin.M_Product_ID,lin.QtyInvoiced "
                    + "HAVING "
                    + (matched ? "0" : "lin.QtyInvoiced")
                    + "<>SUM(NVL(mi.Qty,0))";
            }
            else if (display == MATCH_ORDER)
            {
                checkGrid = 2;
                _dateColumn = "hdr.DateOrdered";
                _qtyColumn = "lin.QtyOrdered";
                _sql.Append("SELECT 'false' as SELECTROW,hdr.C_Order_ID AS C_ORDER_ID,hdr.DocumentNo AS DOCUMENTNO, hdr.DateOrdered AS DATE1, bp.Name AS BPNAME,hdr.C_BPartner_ID AS C_BPARTNER_ID,"
                    + " lin.Line AS LINE,lin.C_OrderLine_ID AS C_ORDERLINE_ID, p.Name AS PNAME,lin.M_Product_ID AS M_PRODUCT_ID,"
                    + " lin.QtyOrdered AS QTYORDERED,SUM(COALESCE(mo.Qty,0)) AS MQTY "
                    + "FROM C_Order hdr"
                    + " INNER JOIN C_BPartner bp ON (hdr.C_BPartner_ID=bp.C_BPartner_ID)"
                    + " INNER JOIN C_OrderLine lin ON (hdr.C_Order_ID=lin.C_Order_ID)"
                    + " INNER JOIN M_Product p ON (lin.M_Product_ID=p.M_Product_ID)"
                    + " INNER JOIN C_DocType dt ON (hdr.C_DocType_ID=dt.C_DocType_ID AND dt.DocBaseType='POO'AND dt.isReturnTrx = ")
                    .Append(((bool)vchkIsReturnTrx.IsChecked) ? "'Y')" : "'N')")
                    .Append(" FULL JOIN M_MatchPO mo ON (lin.C_OrderLine_ID=mo.C_OrderLine_ID) "
                    + "WHERE mo.")
                    .Append(matchToType == MATCH_SHIPMENT ? "M_InOutLine_ID" : "C_InvoiceLine_ID")
                    .Append(matched ? " IS NOT NULL" : " IS NULL"
                    + " AND hdr.DocStatus IN ('CO','CL')");
                _groupBy = " GROUP BY hdr.C_Order_ID,hdr.DocumentNo,hdr.DateOrdered,bp.Name,hdr.C_BPartner_ID,"
                    + " lin.Line,lin.C_OrderLine_ID,p.Name,lin.M_Product_ID,lin.QtyOrdered "
                    + "HAVING "
                    + (matched ? "0" : "lin.QtyOrdered")
                    + "<>SUM(COALESCE(mo.Qty,0))";
            }
            else    //  Shipment
            {
                checkGrid = 3;
                _dateColumn = "hdr.MovementDate";
                _qtyColumn = "lin.MovementQty";
                _sql.Append("SELECT 'false' as SELECTROW,hdr.M_InOut_ID AS M_INOUT_ID,hdr.DocumentNo AS DOCUMENTNO, hdr.MovementDate AS DATE1, bp.Name AS BPNAME, hdr.C_BPartner_ID AS C_BPARTNER_ID,"
                    + " lin.Line AS LINE,lin.M_InOutLine_ID AS M_INOUTLINE_ID, p.Name AS PNAME,lin.M_Product_ID AS M_PRODUCT_ID,"
                    + " lin.MovementQty AS MOVEMENTQTY,SUM(NVL(m.Qty,0)) AS MQTY "
                    + "FROM M_InOut hdr"
                    + " INNER JOIN C_BPartner bp ON (hdr.C_BPartner_ID=bp.C_BPartner_ID)"
                    + " INNER JOIN M_InOutLine lin ON (hdr.M_InOut_ID=lin.M_InOut_ID)"
                    + " INNER JOIN M_Product p ON (lin.M_Product_ID=p.M_Product_ID)"
                    + " INNER JOIN C_DocType dt ON (hdr.C_DocType_ID = dt.C_DocType_ID AND dt.DocBaseType='MMR' AND dt.isReturnTrx = ")
                    .Append(((bool)(vchkIsReturnTrx.IsChecked)) ? "'Y')" : "'N')")
                    .Append(" FULL JOIN ")
                    .Append(matchToType == MATCH_ORDER ? "M_MatchPO" : "M_MatchInv")
                    .Append(" m ON (lin.M_InOutLine_ID=m.M_InOutLine_ID) "
                    + "WHERE hdr.DocStatus IN ('CO','CL')");
                _groupBy = " GROUP BY hdr.M_InOut_ID,hdr.DocumentNo,hdr.MovementDate,bp.Name,hdr.C_BPartner_ID,"
                    + " lin.Line,lin.M_InOutLine_ID,p.Name,lin.M_Product_ID,lin.MovementQty "
                    + "HAVING "
                    + (matched ? "0" : "lin.MovementQty")
                    + "<>SUM(NVL(m.Qty,0))";
            }
            //	Log.trace(7, "VMatch.tableInit", _sql + "\n" + _groupBy);
        }

        /// <summary>
        /// Fill the table using _sql
        /// </summary>
        /// <param name="table">GRid</param>
        private DataSet TableLoad(SLControls.Controls.VDataGrid table)
        {
            //	//log.finest(_sql + " - " +  _groupBy);
            String sql = MRole.GetDefault().AddAccessSQL(
                _sql.ToString(), "hdr", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO)
                + _groupBy;
            log.Finest(sql);
            DataSet ds = new DataSet();


            try
            {
                ds = DB.ExecuteDataset(sql, null);
                //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => ExecuteQuery(table, ds));

            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql, e);
            }
            return ds;
        }
        //table.loadTable(rs);
        // table.Rows.Clear();
        //table.DataSource = null;
        public void ExecuteQuery(SLControls.Controls.VDataGrid table, DataSet ds)
        {
            //vdgvInvoice.AutoGenerateColumns = true;
            //DataColumn dc = null;
            // DataTable dt = new DataTable();
            #region CommentedCode
            //             try
            //            {
            //                object[] finalData = new object[_Layout.Length];
            //                DataTable dt = new DataTable();
            //                if (ds == null)
            //                {
            //                    log.Log(Level.SEVERE, sql, "");
            //                }
            //                else
            //                {
            //                    //vdgvRecords.DataSource = dr;
            //                    for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            //                    {
            //                        int colOffset = 0;  //  columns start with 1
            //                        for (int col = 0; col < _Layout.Length; col++)
            //                        {
            //                            Object data = null;
            //                            Type c = _Layout[col].GetColClass();
            //                            int colIndex = col + colOffset;

            //                            //if (col == 1 && i == 0)
            //                            //    _Layout[col].SetColHeader(_Layout[col].GetColHeader() + "_ID");
            //                            //dt.Columns.Add(_Layout[col].GetColHeader(), c);

            //                            if (i == 0)
            //                            {
            //                                if (c == typeof(DateTime))
            //                                {
            //                                    dc = new DataColumn(_Layout[col].GetColHeader(), typeof(string));
            //                                    dt.Columns.Add(dc);   //n
            //                                   // datarow.Table.Columns.Add(dc);
            //                                }
            //                                else
            //                                {
            //                                    dc = new DataColumn(_Layout[col].GetColHeader(), c);
            //                                    dt.Columns.Add(dc);   //n
            //                                    //datarow.Table.Columns.Add(dc);
            //                                }
            //                            }


            //                            if (c == typeof(IDColumn))
            //                            {
            //                                data = new IDColumn(Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex].ToString()));
            //                                finalData[col] = data;

            //                                //dt.Rows.Add(data, typeof(IDColumn));

            //                            }
            //                            else if (c == typeof(Boolean))
            //                            {
            //                                data = "Y".Equals(ds.Tables[0].Rows[i][colIndex].ToString());
            //                                finalData[col] = data;

            //                                //datarow.SetValue(colname, data);

            //                                //dt.Rows.Add(data, typeof(bool));
            //                            }
            //                            else if (c == typeof(DateTime))
            //                            {
            //                                if (ds.Tables[0].Rows[i][colIndex].ToString() != "")
            //                                {
            //                                    data = DateTime.Parse(ds.Tables[0].Rows[i][colIndex].ToString());
            //                                    finalData[col] = data;


            //                                    //datarow.SetValue(colname, data);
            //                                    //dt.Rows.Add(data, typeof(DateTime));
            //                                }
            //                                else
            //                                {
            //                                    data = "";
            //                                    finalData[col] = data;


            //                                    //datarow.SetValue(colname, data);
            //                                    //dt.Rows.Add(data, typeof(string));
            //                                }
            //                            }
            //                            else if (c == typeof(Decimal))
            //                            {
            //                                data = Util.GetValueOfDecimal(ds.Tables[0].Rows[i][colIndex].ToString());
            //                                finalData[col] = data;


            ////                                datarow.SetValue(colname, data);
            //                                //dt.Rows.Add(data, typeof(decimal));
            //                            }
            //                            else if (c == typeof(Double))
            //                            {
            //                                data = Util.GetValueOfDecimal(ds.Tables[0].Rows[i][colIndex].ToString());
            //                                finalData[col] = data;

            //                              //  datarow.SetValue(colname, data);

            //                                //dt.Rows.Add(data, typeof(Double));
            //                            }
            //                            else if (c == typeof(Int32))
            //                            {
            //                                data = Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex].ToString());
            //                                finalData[col] = data;


            //                                //datarow.SetValue(colname, data);
            //                                //dt.Rows.Add(data, typeof(Int32));
            //                            }
            //                            //else if (c == typeof(KeyNamePair))
            //                            //{
            //                            //    Object display = ds.Tables[0].Rows[i][colIndex].ToString();
            //                            //    int key = ds.Tables[0].Rows[i][colIndex].ToString() != "" ? Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex + 1].ToString()) : 0;
            //                            //    data = new KeyNamePair(key, display.ToString());
            //                            //    finalData[col] = data;
            //                            //    //dt.Rows.Add(data, typeof(KeyNamePair));
            //                            //    colOffset++;
            //                            //}
            //                            else if (c == typeof(String))
            //                            {
            //                                data = ds.Tables[0].Rows[i][colIndex].ToString();
            //                                finalData[col] = data;
            //                                //datarow.SetValue(colname, data);
            //                            }
            //                            else if (c == typeof(int))
            //                            {
            //                                data = ds.Tables[0].Rows[i][colIndex].ToString() != "" ? Util.GetValueOfInt(ds.Tables[0].Rows[i][colIndex + 1].ToString()) : 0;
            //                                finalData[col] = data;


            //                                //datarow.SetValue(colname, data);
            //                            }
            //                            else
            //                            {
            //                                data = ds.Tables[0].Rows[i][colIndex].ToString();
            //                                finalData[col] = data;


            //                                //datarow.SetValue(colname, data);
            //                                //dt.Rows.Add(data, typeof(string));
            //                            }

            //                            //DataGridViewCheckBoxColumn
            //                            //vdgvRecords.Rows[row].Cells[col].Value = data;  //set the records value in grid view
            //                        }

            //                        DataRow dr2 = dt.NewRow();



            //                        for (int k = 0; k < finalData.Count(); k++)
            //                        {
            //                            dr2[k] = finalData.GetValue(k);
            //                        }

            //                        dt.Rows.Add(dr2);
            //                        //dt.Rows.Add(finalData);
            //                    }
            //                    ds.Dispose();
            //                    ds = null;
            //                }
            //}
            #endregion
            //DataGridTextColumn order = new DataGridTextColumn();
            //order.Header = Msg.Translate(Envs.GetContext(), "C_order_ID");
            //order.Binding = new System.Windows.Data.Binding("C_ORDER_ID");
            //order.Visibility = Visibility.Collapsed;
            table.AutoGenerateColumns = false;
            table.Columns.Clear();
            if (table.Name == "vdgvReceipt")
            {
                table.AutoGenerateColumns = false;
                table.ItemsSource = null;
                table.Columns.Clear();
                chk.Header = Msg.GetMsg(Envs.GetCtx(), "SELECTROW");
                chk.Binding = new System.Windows.Data.Binding("SELECTROW");
                chk.DataPropertyName = "SELECTROW";
                chk.DataGrid = table;
                chk.IsThreeState = false;
                chk.IsReadOnly = false;
                //chk.Click += new RoutedEventHandler(chk_Click);
                //chk.PropertyChanged += new PropertyChangedEventHandler(chk_PropertyChanged);
                table.Columns.Add(chk);
            }

            if (checkGrid == 1)
            {
                DataGridTextColumn txtID = new DataGridTextColumn();
                txtID.Header = Msg.Translate(Envs.GetContext(), "C_INVOICE_ID");
                txtID.Binding = new System.Windows.Data.Binding("C_INVOICE_ID");
                txtID.IsReadOnly = true;
                txtID.Visibility = Visibility.Collapsed;
                table.Columns.Add(txtID);
            }
            else if (checkGrid == 2)
            {
                DataGridTextColumn txtID = new DataGridTextColumn();
                txtID.Header = Msg.Translate(Envs.GetContext(), "C_ORDER_ID");
                txtID.Binding = new System.Windows.Data.Binding("C_ORDER_ID");
                txtID.IsReadOnly = true;
                txtID.Visibility = Visibility.Collapsed;
                table.Columns.Add(txtID);
            }
            else
            {
                DataGridTextColumn txtID = new DataGridTextColumn();
                txtID.Header = Msg.Translate(Envs.GetContext(), "M_INOUT_ID");
                txtID.Binding = new System.Windows.Data.Binding("M_INOUT_ID");
                txtID.IsReadOnly = true;
                txtID.Visibility = Visibility.Collapsed;
                table.Columns.Add(txtID);
            }

            DataGridTextColumn txt1 = new DataGridTextColumn();
            txt1.Header = Msg.Translate(Envs.GetContext(), "DOCUMENT NO");
            txt1.Binding = new System.Windows.Data.Binding("DOCUMENTNO");
            txt1.IsReadOnly = true;
            table.Columns.Add(txt1);



            DataGridTextColumn txt4 = new DataGridTextColumn();
            txt4.Header = Msg.Translate(Envs.GetContext(), "DATE");
            txt4.Binding = new System.Windows.Data.Binding("DATE1");
            txt4.IsReadOnly = true;
            table.Columns.Add(txt4);
            DataGridTextColumn txt5 = new DataGridTextColumn();
            txt5.Header = Msg.Translate(Envs.GetContext(), "BUSINESS PARTNER");
            txt5.Binding = new System.Windows.Data.Binding("BPNAME");
            txt5.IsReadOnly = true;
            table.Columns.Add(txt5);
            DataGridTextColumn txt6 = new DataGridTextColumn();
            txt6.Header = Msg.Translate(Envs.GetContext(), "C_BPARTNER_ID");
            txt6.Binding = new System.Windows.Data.Binding("C_BPARTNER_ID");
            txt6.IsReadOnly = true;
            txt6.Visibility = Visibility.Collapsed;
            table.Columns.Add(txt6);
            DataGridTextColumn txt2 = new DataGridTextColumn();
            txt2.Header = Msg.Translate(Envs.GetBaseAD_Language(), "LINE");
            txt2.Binding = new System.Windows.Data.Binding("LINE");
            txt2.IsReadOnly = true;
            table.Columns.Add(txt2);

            if (checkGrid == 1)
            {
                DataGridTextColumn txt7 = new DataGridTextColumn();
                txt7.Header = Msg.Translate(Envs.GetBaseAD_Language(), "C_INVOICELINE_ID");
                txt7.Binding = new System.Windows.Data.Binding("C_INVOICELINE_ID");
                txt7.IsReadOnly = true;
                txt7.Visibility = Visibility.Collapsed;
                table.Columns.Add(txt7);
            }
            else if (checkGrid == 2)
            {
                DataGridTextColumn txt7 = new DataGridTextColumn();
                txt7.Header = Msg.Translate(Envs.GetBaseAD_Language(), "C_ORDERLINE_ID");
                txt7.Binding = new System.Windows.Data.Binding("C_ORDERLINE_ID");
                txt7.IsReadOnly = true;
                txt7.Visibility = Visibility.Collapsed;
                table.Columns.Add(txt7);

            }
            else
            {
                DataGridTextColumn txt7 = new DataGridTextColumn();
                txt7.Header = Msg.Translate(Envs.GetBaseAD_Language(), "M_InOutLine_ID");
                txt7.Binding = new System.Windows.Data.Binding("M_InOutLine_ID");
                txt7.IsReadOnly = true;
                txt7.Visibility = Visibility.Collapsed;
                table.Columns.Add(txt7);
            }


            DataGridTextColumn txt8 = new DataGridTextColumn();
            txt8.Header = Msg.Translate(Envs.GetBaseAD_Language(), "PRODUCT");
            txt8.Binding = new System.Windows.Data.Binding("PNAME");
            txt8.IsReadOnly = true;
            table.Columns.Add(txt8);
            DataGridTextColumn txt9 = new DataGridTextColumn();
            txt9.Header = Msg.Translate(Envs.GetBaseAD_Language(), "M_PRODUCT_ID");
            txt9.Binding = new System.Windows.Data.Binding("M_PRODUCT_ID");
            txt9.Visibility = Visibility.Collapsed;
            txt9.IsReadOnly = true;
            table.Columns.Add(txt9);
            if (checkGrid == 1)
            {
                DataGridTextColumn txt3 = new DataGridTextColumn();
                txt3.Header = Msg.Translate(Envs.GetBaseAD_Language(), "QUANTITY");
                txt3.Binding = new System.Windows.Data.Binding("QTYINVOICED");
                txt3.IsReadOnly = true;
                table.Columns.Add(txt3);
            }
            else if (checkGrid == 2)
            {
                DataGridTextColumn txt3 = new DataGridTextColumn();
                txt3.Header = Msg.Translate(Envs.GetBaseAD_Language(), "QUANTITY");
                txt3.Binding = new System.Windows.Data.Binding("QTYORDERED");
                txt3.IsReadOnly = true;
                table.Columns.Add(txt3);
            }
            else
            {
                DataGridTextColumn txt3 = new DataGridTextColumn();
                txt3.Header = Msg.Translate(Envs.GetBaseAD_Language(), "QUANTITY");
                txt3.Binding = new System.Windows.Data.Binding("MOVEMENTQTY");
                txt3.IsReadOnly = true;
                table.Columns.Add(txt3);
            }
            DataGridTextColumn txt11 = new DataGridTextColumn();
            txt11.Header = Msg.Translate(Envs.GetBaseAD_Language(), "Matched");
            txt11.Binding = new System.Windows.Data.Binding("MQTY");
            txt11.IsReadOnly = true;
            table.Columns.Add(txt11);

            if (table.Name == "vdgvInvoice")
            {
                BindingSource source = new BindingSource(ds.Tables[0].GetBindableData(new Connector()));
                table.ItemsSource = source;
               // table.ItemsSource = ds.Tables[0].GetBindableData(new Connector());

            }
            if (table.Columns.Count > 0)
            {
                table.SelectedIndex = 0;
            }
            //if (dt.Columns.Count < 1)
            //{

            //   // AddColumns(table.Name == "vdgvReceipt");
            //    //return;
            //}
            if (table.Name == "vdgvReceipt")
            {
                BindingSource source=new BindingSource(ds.Tables[0].GetBindableData(new Connector()));
                table.ItemsSource = source;
                //}
                //   if (table.Name == "vdgvReceipt")
                //   {
                //chk.Header = Msg.GetMsg(Envs.GetCtx(), "SELECTROW");
                //chk.Binding = new System.Windows.Data.Binding("SELECTROW");
                //chk.DataPropertyName = "SELECTROW";
                //chk.DataGrid = vdgvReceipt;
                //chk.IsThreeState = false;
                //chk.IsReadOnly = false;
                //chk.Click += new RoutedEventHandler(chk_Click);
                //chk.PropertyChanged += new PropertyChangedEventHandler(chk_PropertyChanged);
                //vdgvReceipt.Columns.Add(chk);

                //DataGridCheckBoxColumn chkInv = new DataGridCheckBoxColumn();
                //chkInv.Header = "Select";

                if ((bool)vchkSameProduct.IsChecked)
                {
                    chk.IsReadOnly = false;
                }
                else
                {
                    chk.IsReadOnly = true;
                }
                chk.Width = new DataGridLength(20);

                //table.Columns.Insert(0, chk);
                table.Columns[0].IsReadOnly = !((bool)vchkSameProduct.IsChecked);
                table.Columns[1].IsReadOnly = true;
                table.Columns[2].IsReadOnly = true;
                table.Columns[3].IsReadOnly = true;
                table.Columns[4].IsReadOnly = true;
                table.Columns[5].IsReadOnly = true;
                table.Columns[6].IsReadOnly = true;
                table.Columns[7].IsReadOnly = true;
                table.Columns[8].IsReadOnly = true;
            }

        }

        //void table_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    if (e.ToString() == "vdgvInvoice")
        //    {
        //        Cursor = Cursors.Wait;
        //        Cmd_SearchTo();
        //        Cursor = Cursors.Arrow;
        //    }
        //    if (e.ToString() == "vdgvReceipt") 
        //    {
        //        TableChanged();
        //    }
        //}

        void chk_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            //throw new NotImplementedException();
        }

        bool bVal = false;

        void chk_Click(object sender, RoutedEventArgs e)
        {
            //IList rowReceipt = vdgvReceipt.ItemsSource as IList;
            BindingSource rowReceipt = vdgvReceipt.ItemsSource as BindingSource;
            if ((bool)vchkSameProduct.IsChecked)
            {
                // Object val = vdgvReceipt.Rows[e.RowIndex].Cells[0].Value;
                String val = ((BindableObject)rowReceipt[vdgvReceipt.SelectedIndex]).GetValue(0);

                if (val == "false" || val == "null")
                {
                    bVal = true;
                    //vdgvReceipt.Rows[e.RowIndex].Cells[0].Value = true;
                    ((BindableObject)rowReceipt[vdgvReceipt.SelectedIndex]).SetValue(0, "true");
                }
                else
                {
                    bVal = false;
                    //vdgvReceipt.Rows[e.RowIndex].Cells[0].Value = null;
                    ((BindableObject)rowReceipt[vdgvReceipt.SelectedIndex]).SetValue(0, "false");
                }

                //IDColumn id = (IDColumn)vdgvReceipt.Rows[e.RowIndex].Cells[1].Value;
                // IDColumn id = (IDColumn)((BindableObject)rowReceipt[vdgvReceipt.SelectedIndex]).GetValue(1);
                int id = Convert.ToInt32(((BindableObject)rowReceipt[vdgvReceipt.SelectedIndex]).GetValue(1));
                //id.SetSelected(bVal);
                TableChanged();
            }
        }

        /// <summary>
        /// Create Matching Record
        /// </summary>
        /// <param name="invoice">true if matching invoice false if matching PO</param>
        /// <param name="M_InOutLine_ID">shipment line</param>
        /// <param name="Line_ID">C_InvoiceLine_ID or C_OrderLine_ID</param>
        /// <param name="qty">quantity</param>
        /// <returns>true if created</returns>
        public static Boolean CreateMatchRecord(Boolean invoice, int M_InOutLine_ID, int Line_ID, Decimal qty)
        {
            Trx trx = Trx.Get("MatchPO", true);

            if (qty.CompareTo(Envs.ZERO) == 0)
                return true;
            log.Fine("IsInvoice=" + invoice
                + ", M_InOutLine_ID=" + M_InOutLine_ID + ", Line_ID=" + Line_ID
                + ", Qty=" + qty);
            //
            Boolean success = false;

            try
            {

                MInOutLine sLine = new MInOutLine(Envs.GetCtx(), M_InOutLine_ID, trx.GetTrxName());
                if (invoice)	//	Shipment - Invoice
                {
                    //	Update Invoice Line
                    MInvoiceLine iLine = new MInvoiceLine(Envs.GetCtx(), Line_ID, trx.GetTrxName());
                    iLine.SetM_InOutLine_ID(M_InOutLine_ID);
                    if (sLine.GetC_OrderLine_ID() != 0)
                        iLine.SetC_OrderLine_ID(sLine.GetC_OrderLine_ID());
                    iLine.Save();
                    //	Create Shipment - Invoice Link
                    if (iLine.GetM_Product_ID() != 0)
                    {
                        try
                        {
                            MMatchInv match = new MMatchInv(iLine, null, qty);
                            match.SetM_InOutLine_ID(M_InOutLine_ID);
                            if (match.Save())
                                success = true;
                            else
                                log.Log(Level.SEVERE, "Inv Match not created: " + match);
                        }
                        catch (Exception e)
                        {
                            log.Log(Level.SEVERE, "Inv Match not created: " + e.Message);
                        }
                    }
                    else
                        success = true;
                    //	Create PO - Invoice Link = corrects PO
                    if (iLine.GetC_OrderLine_ID() != 0 && iLine.GetM_Product_ID() != 0)
                    {
                        try
                        {
                            MMatchPO matchPO = MMatchPO.Create(iLine, sLine, null, qty);
                            matchPO.SetC_InvoiceLine_ID(iLine);
                            matchPO.SetM_InOutLine_ID(M_InOutLine_ID);
                            if (!matchPO.Save())
                                log.Log(Level.SEVERE, "PO(Inv) Match not created: " + matchPO);
                        }
                        catch (Exception e)
                        {
                            log.Log(Level.SEVERE, "PO(Inv) Match not created: " + e.Message);
                        }
                    }
                }
                else	//	Shipment - Order
                {
                    //	Update Shipment Line
                    sLine.SetC_OrderLine_ID(Line_ID);
                    sLine.Save();
                    //	Update Order Line
                    MOrderLine oLine = new MOrderLine(Envs.GetCtx(), Line_ID, trx.GetTrxName());
                    if (oLine.Get_ID() != 0)	//	other in MInOut.completeIt
                    {
                        //oLine.SetQtyReserved(oLine.GetQtyReserved().subtract(qty));
                        oLine.SetQtyReserved(Decimal.Subtract(oLine.GetQtyReserved(), qty));
                        if (!oLine.Save())
                            log.Severe("QtyReserved not updated - C_OrderLine_ID=" + Line_ID);
                    }

                    //	Create PO - Shipment Link
                    if (sLine.GetM_Product_ID() != 0)
                    {
                        MMatchPO match = new MMatchPO(sLine, null, qty);
                        if (!match.Save())
                            log.Log(Level.SEVERE, "PO Match not created: " + match);
                        else
                        {
                            success = true;
                            //	Correct Ordered Qty for Stocked Products (see MOrder.reserveStock / MInOut.processIt)
                            if (sLine.GetProduct() != null && sLine.GetProduct().IsStocked())
                                success = MStorage.Add(Envs.GetCtx(), sLine.GetM_Warehouse_ID(),
                                    sLine.GetM_Locator_ID(),
                                    sLine.GetM_Product_ID(),
                                    sLine.GetM_AttributeSetInstance_ID(), oLine.GetM_AttributeSetInstance_ID(),
                                    0, null, Decimal.Negate(qty), null);
                        }
                    }
                    else
                    {
                        success = true;
                    }
                }
                if (success)
                {
                    trx.Commit();
                }
                else
                {
                    trx.Rollback();
                }

            }
            catch (Exception e)
            {
                success = false;
                trx.Rollback();
            }
            finally
            {
                trx.Close();
            }

            return success;
        }

        #region BackGroundThread
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            log.Info("Starting ...");
            MMatchPO.Consolidate(Envs.GetCtx());

        }

        private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            log.Info("... Done");
        }
        #endregion

        private void vcmbMatchFrom_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            DynInit();
            Cmd_MatchFrom();

        }

        private void vcmbMatchTo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            Cmd_MatchTo();

        }

        private void vbtnSearch_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            Cmd_Search();

        }

        private void vbtnProcess_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            Cmd_Process();

        }

        private void vchkSameBPartner_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            Cmd_SearchTo();
        }

        private void vchkSameQty_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            Cmd_SearchTo();

        }

        private void vchkSameProduct_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            Cmd_SearchTo();

        }

        private void vdgvInvoice_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SetBusy(true);
            Cmd_SearchTo();

        }

        private void vdgvReceipt_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TableChanged();
        }

        public void TableChanged()
        {
            //IList rowInvoice = vdgvInvoice.ItemsSource as IList;
            //IList rowReceipt = vdgvReceipt.ItemsSource as IList;

            BindingSource rowInvoice = vdgvInvoice.ItemsSource as BindingSource;
            BindingSource rowReceipt = vdgvReceipt.ItemsSource as BindingSource;

            //  Matched From
            if (rowInvoice==null)
            {
                return;
            }
            int matchedRow = -1;

            if (vdgvInvoice.SelectedItems.Count > 0)
            {
                if (vdgvInvoice.SelectedIndex == 0)
                {
                    matchedRow = 0;
                }
                else
                {
                    matchedRow = vdgvInvoice.SelectedIndex;
                }
            }
            //int matchedRow = xMatchedTable.getSelectedRow();
            //KeyNamePair Product = (KeyNamePair)vdgvInvoice.Rows[matchedRow].Cells[5].Value;
            int Product = Convert.ToInt32(((BindableObject)rowInvoice[matchedRow]).GetValue(9));
            //  Matched To
            double qty = 0.0;
            int noRows = 0;
            int newColumn = 0;
            if (vdgvReceipt.Columns.Count == 13)
            {
                newColumn = 1;
            }

            for (int row = 0; row < rowReceipt.Count; row++)//xMatchedToTable
            {

                // IDColumn id = (IDColumn)vdgvReceipt.Rows[row].Cells[0 + newColumn].Value;// xMatchedToTable.getValueAt(row, 0);
                //IDColumn id = (IDColumn)(((BindableObject)rowReceipt[row]).GetValue(0 + newColumn));
                int id = Convert.ToInt32(((BindableObject)rowReceipt[row]).GetValue(1));
                // if (id != null && id.IsSelected())

                string chk = ((BindableObject)rowReceipt[row]).GetValue(0);


                if (id != 0 && chk == "True"||chk== "true")// vdgvReceipt.SelectedIndex))
                {
                   // if (row == vdgvReceipt.SelectedIndex)
                    {
                        //KeyNamePair ProductCompare = (KeyNamePair)vdgvReceipt.Rows[row].Cells[5 + newColumn].Value;//xMatchedToTable.getValueAt(row, 5);
                        int ProductCompare = Convert.ToInt32(((BindableObject)rowReceipt[row]).GetValue(9));
                        if (Product != ProductCompare)
                        {
                            //id.SetSelected(false);
                        }
                        else
                        {
                            //if (vcmbMatchMode.SelectedIndex == MODE_NOTMATCHED)
                            //{
                            //    qty += Util.GetValueOfDouble(vdgvReceipt.Rows[row].Cells[I_QTY + newColumn].Value);// xMatchedToTable.getValueAt(row, I_QTY)); // doc
                            //}
                            //qty -= Util.GetValueOfDouble(vdgvReceipt.Rows[row].Cells[I_MATCHED + newColumn].Value);//xMatchedToTable.getValueAt(row, I_MATCHED)); // matched

                            if (vcmbMatchMode.SelectedIndex == MODE_NOTMATCHED)
                            {
                                qty += Util.GetValueOfDouble(((BindableObject)rowReceipt[row]).GetValue(10));// xMatchedToTable.getValueAt(row, I_QTY)); // doc
                            }
                            qty -= Util.GetValueOfDouble(((BindableObject)rowReceipt[row]).GetValue(11));//xMatchedToTable.getValueAt(row, I_MATCHED)); // matched
                            noRows++;
                        }
                    }
                }
            }
            //  update quantities
            _xMatchedTo = Util.GetValueOfDecimal(qty);
            vtxtMatchedTo.Text = _xMatchedTo.ToString();
            //txtDifference.SetValue(_xMatched.subtract(_xMatchedTo));
            vtxtDifference.Text = (Decimal.Subtract(_xMatched, _xMatchedTo)).ToString();
            vbtnProcess.IsEnabled = (noRows != 0);
            // setCursor(Cursor.getDefaultCursor());

            //  Status
            vStatusBar.SetStatusDB(noRows);
        }


        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

    }
}
